package com.cpone.cloudweb.utils.bak;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class ClientSocket extends Thread{
	
	private Socket socket;
	private InputStream in;
	private OutputStream out;
	//private static int counter = 0;
	//private int id = counter++;
	private Integer id;
	private String filePathName;
	private int socketStatus;//0为通信出错
	private static int threadcount = 0;
	
	public static int threadCount() { 
		return threadcount;
	}
	
	public ClientSocket(InetAddress addr, Integer port, Integer pcmId, String fileName) {
		this.id = pcmId;
		this.filePathName = fileName;
		System.out.println("Making client " + id);
		threadcount++;
		try{
			socket =  new Socket(addr, port);
			//new Socket(addr, 9899);
		}catch(IOException e) {
			e.printStackTrace();
			socket = null;
		}
		if(null!=socket.toString()){
			try{
				in = socket.getInputStream();
				out = socket.getOutputStream();
				start();
			}catch(IOException e){
				try{
					socket.close();
					socket = null;
				}catch(IOException e2){
					e2.printStackTrace();
					socket = null;
				}
			}
		}
	}
	  
	public void run() {
		 // File myFile = null;
		 // RandomAccessFile outNew =null;
	    try {
	    	byte[] buf = new byte[12];
	    	byte[] bufByte = "RWXF".getBytes();
	    	System.arraycopy(bufByte, 0, buf, 0, bufByte.length);
	    	byte[] idByteS = writeBigEndianInt(1);
	    	System.arraycopy(idByteS, 0, buf, 4, idByteS.length);
	    	byte[] statusByteS = writeBigEndianInt(1);
	    	System.arraycopy(statusByteS, 0, buf, 8, statusByteS.length);
	    	out.write(buf);
	    	out.flush();
	    	
	    	byte[] strByte = new byte[4];
	    	in.read(strByte);
	    	byte[] idByte = new byte[4];
	    	in.read(idByte);
	    	byte[] statusByte = new byte[4];
	    	in.read(statusByte);
	    	
	    	String str = new String(strByte);
	    	int id = readBigEndianInt(idByte);
	    	int status = readBigEndianInt(statusByte); 
	    	System.out.println("通知回复--包头："+str);
	    	System.out.println("通知回复--标示ID:"+id);
	    	System.out.println("通知回复--任务状态："+status);
	    	
	    	
	    	if(str.equals("RWXF")&&id==2&&status==2){
	    		int len = this.filePathName.getBytes().length;
	    		int length = 4+4+8+8+len;
	    		byte[] buf2 = new byte[length];
	    		bufByte = "RWXF".getBytes();
		    	System.arraycopy(bufByte, 0, buf2, 0, bufByte.length);
		    	
		    	idByteS = writeBigEndianInt(3);
		    	System.arraycopy(idByteS, 0, buf2, 4, idByteS.length);
		    	
		    	byte[] dataIdByte = writeBigEndianLong(this.id);
		    	System.arraycopy(dataIdByte, 0, buf2, 8, dataIdByte.length);
		    	
		    	byte[] dataLenByte = writeBigEndianLong(len);
		    	System.arraycopy(dataLenByte, 0, buf2, 16, dataLenByte.length);

		    	byte[] dataByte = this.filePathName.getBytes();
		    	System.arraycopy(dataByte, 0, buf2, 24, dataByte.length);
		    	out.write(buf2);
		    	out.flush();
	    	}
	    	strByte = new byte[4];
	    	in.read(strByte);
	    	statusByte = new byte[4];
	    	in.read(statusByte);
	    	byte[] idsByte = new byte[8];
	    	in.read(idsByte);
	    	byte[] lenByte = new byte[8];
	    	in.read(lenByte);
	    	str = new String(strByte);
	    	status = readBigEndianInt(statusByte);
	    	long ids = readBigEndianLong(idsByte);
	    	long len = readBigEndianLong(lenByte);
	    	
	    	System.out.println("结果回复--包头："+str);
	    	System.out.println("结果回复--状态："+status);
	    	System.out.println("结果回复--数据ID："+ids);
	    	System.out.println("结果回复--数据长度："+len);
	    	
	    	this.socketStatus = 9;
	    	
	    	/*if(str.equals("RWXF")&&status==4&&ids==1L){
	    		System.out.println("通信符合要求开始接收数据");
	    		byte[] dataStr = new byte[Long.valueOf(len).intValue()];
		    	int ddle = in.read(dataStr);
		    	System.out.println(ddle);
		    	String xml = new String(dataStr,"UTF-8");
		        //new File("D:\\file\\file\\").mkdirs();
				myFile = new File(this.filePathName);
				outNew = new RandomAccessFile(myFile ,"rw");
				outNew.writeUTF(xml);
		        System.out.println("接受到的数据:"+xml);
	    	}else{
	    		System.out.println("通信协议出错，本次通话结束！");
	    	}*/
	    	
	    } catch(Exception e) {
	    } finally {
	      try {
	    	  in.close();
	    	  out.close();
	        socket.close();
	      } catch(IOException e) {}
	      threadcount--; // Ending this thread
	    }
	  }
	
	 public final static byte[] writeInt(int n){//************************
		 	byte[] b = new byte[4];   
	        b[0] = (byte) (n >> 24 & 0xff);   
	        b[1] = (byte) (n >> 16 & 0xff);   
	        b[2] = (byte) (n >> 8 & 0xff);   
	        b[3] = (byte) (n >> 0 & 0xff);
	        return b;
	    }
	 private static byte[] writeBigEndianInt(int n) {   
	        byte[] b = new byte[4];   
	        b[0] = (byte) (n & 0xff);   
	        b[1] = (byte) (n >> 8 & 0xff);   
	        b[2] = (byte) (n >> 16 & 0xff);   
	        b[3] = (byte) (n >> 24 & 0xff);   
	       return b;   
	    }
	 public final static byte[] writeLong(long v) throws IOException {//***********************
		   byte[] writeBuffer = new byte[8];
	        writeBuffer[0] = (byte)(v >>> 56);
	        writeBuffer[1] = (byte)(v >>> 48);
	        writeBuffer[2] = (byte)(v >>> 40);
	        writeBuffer[3] = (byte)(v >>> 32);
	        writeBuffer[4] = (byte)(v >>> 24);
	        writeBuffer[5] = (byte)(v >>> 16);
	        writeBuffer[6] = (byte)(v >>>  8);
	        writeBuffer[7] = (byte)(v >>>  0);
	        return writeBuffer;
	    }
	 private static byte[] writeBigEndianLong(long n){
	        byte[] b = new byte[8];   
	        b[0] = (byte) (n & 0xff);   
	        b[1] = (byte) (n >> 8 & 0xff);   
	        b[2] = (byte) (n >> 16 & 0xff);   
	        b[3] = (byte) (n >> 24 & 0xff);
	        b[4] = (byte) (n >> 32 & 0xff);   
	        b[5] = (byte) (n >> 40 & 0xff);   
	        b[6] = (byte) (n >> 48 & 0xff);
	        b[7] = (byte) (n >> 56 & 0xff);
	        return b;
	 }
	 public final static int readInt(byte[] b) throws IOException {//*********************
	        int ch1 = b[0];
	        int ch2 = b[1];
	        int ch3 = b[2];
	        int ch4 = b[3];
	        if ((ch1 | ch2 | ch3 | ch4) < 0)
	            throw new EOFException();
	        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
	    }
	 public final static int readBigEndianInt(byte[] b) throws IOException {
	        int ch1 = b[0];
	        int ch2 = b[1];
	        int ch3 = b[2];
	        int ch4 = b[3];
	        if ((ch1 | ch2 | ch3 | ch4) < 0)
	            throw new EOFException();
	        return ((ch1 << 0) + (ch2 << 8) + (ch3 << 16) + (ch4 << 24));
	    }
	 
	 public final static long readLong(byte[] b) throws IOException {//**********************
	        return (((long)b[0] << 56) +
	                ((long)(b[1] & 255) << 48) +
	                ((long)(b[2] & 255) << 40) +
	                ((long)(b[3] & 255) << 32) +
	                ((long)(b[4] & 255) << 24) +
	                ((b[5] & 255) << 16) +
	                ((b[6] & 255) <<  8) +
	                ((b[7] & 255) <<  0));
	    }
	 public final static long readBigEndianLong(byte[] b) throws IOException {
	        return ((b[7] << 56) +
	                ((b[6] & 255) << 48) +
	                ((b[5] & 255) << 40) +
	                ((b[4] & 255) << 32) +
	                ((long)(b[3] & 255) << 24) +
	                ((long)(b[2] & 255) << 16) +
	                ((long)(b[1] & 255) <<  8) +
	                ((long)(b[0] & 255) <<  0));
	    }
	 
	public void client_socket(String rwxf, Integer sign, Integer dutyid){
		try{
			byte[] buf = new byte[12];
			byte[] bufByte = rwxf.getBytes();//下发 包头
			System.arraycopy(bufByte, 0, buf, 0, bufByte.length);
			byte[] sigByte = writeBigEndianInt(sign);//下发 标识
			System.arraycopy(sigByte, 0, buf, 0, sigByte.length);
			byte[] idByteS = writeBigEndianInt(dutyid);//下发 检索ID
			System.arraycopy(idByteS, 0, buf, 4, idByteS.length);
			/*byte[] statusByteS = writeBigEndianInt(1);//下发 状态
			System.arraycopy(statusByteS, 0, buf, 8, statusByteS.length);*/
			out.write(buf);
			out.flush();
			
			byte[] strByte = new byte[4];
			in.read(strByte);//回复 收到 包头
			byte[] markByte = new byte[4];
			in.read(markByte);//回复 收到 标识
			byte[] statusByte = new byte[4];
			in.read(statusByte);//回复 收到 状态
			
			
			String str = new String(strByte);
			int mark = readBigEndianInt(markByte);
			int status = readBigEndianInt(statusByte);
			System.out.println("通知回复--包头："+str);
			System.out.println("通知回复--标示:"+mark);
			System.out.println("通知回复--任务状态："+status);
			
			
			if(str.equals("RWXF") && mark==sign && status==2){
				System.out.println("通知回复串客户端已收到");
			}else{
				System.out.println("Scoket通信出错");
			}
			
			strByte = new byte[4];
			in.read(strByte);//回复完成 包头
			markByte = new byte[4];
			in.read(markByte);//回复完成 标识
			statusByte = new byte[4];
			in.read(statusByte);//回复完成 状态
			
			str = new String(strByte);
			mark = readBigEndianInt(markByte);
			status = readBigEndianInt(statusByte); 
			System.out.println("通知完成--包头：" + str);
			System.out.println("通知完成--标识：" + mark);
			System.out.println("通知完成--状态：" + status);
			
			if(str.equals("RWXF") && mark==sign && status==1){
				System.out.println("通知回复串客户端已收到");
			}else{
				System.out.println("Socket通信出错");
			}
		}catch(Exception e){
		}finally{
			try{
				in.close();
				out.close();
				socket.close();
			}catch(IOException e){}
			threadcount--;
		}
	}
	public int getSocketStatus() {
		return socketStatus;
	}
	public void setSocketStatus(int socketStatus) {
		this.socketStatus = socketStatus;
	}
	
}
